<template>
  <div>
    <div class="app-container">
      <h-table-list
        border
        type="local"
        :page-sizes="[10,20]"
        :data="supply.records"
        :columns="columns"
        :pagination-info="paginationInfo"
        :form-options="formOptions"
        @size-change="handleSizeChange"
      >
        <ListOpearteButton />
        <template
          slot="preview-column"
          slot-scope="scope"
        >
          <div :class="'circle-'+scope.row.state" /><span>{{ scope.row.state |formatState }}</span>
        </template>
        <template
          slot="operate-column"
          slot-scope="scope"
        >
          <tableButton :row="scope.row" />
        </template>
      </h-table-list>
    </div>
    <DownloadIdentify
      :visible.sync="dialogFormVisible1"
      title="备件入库"
      @cancel="cancel1"
      @update="dialogSubmit1"
    >
      <el-form
        ref="ruleForm1"
        :model="ruleForm1"
        :rules="rules1"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="备件名称"
          prop="productName"
        >
          <!-- <el-input v-model="ruleForm1.productName" readonly="true"></el-input> -->
          {{ ruleForm1.productName }}
        </el-form-item>
        <el-form-item
          label="备件编号"
          prop="productNumber"
        >
          {{ ruleForm1.productNumber }}
          <!-- <el-input v-model="ruleForm1.productNumber" readonly="true"></el-input> -->
        </el-form-item>
        <el-form-item
          label="入库数量"
          prop="stockNum"
          
        >
          <el-input v-model="ruleForm1.stockNum"  type="number" />
        </el-form-item>

      </el-form>
    </DownloadIdentify>
    <DownloadIdentify
      :visible.sync="dialogFormVisible2"
      title="备件出库"
      @cancel="cancel2"
      @update="dialogSubmit2"
    >
      <el-form
        ref="ruleForm2"
        :model="ruleForm2"
        :rules="rules2"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item
          label="备件名称"
          prop="productName"
        >
          <!-- <el-input v-model="ruleForm2.productName" readonly="true"></el-input> -->
          {{ ruleForm2.productName }}
        </el-form-item>
        <el-form-item
          label="备件编号"
          prop="productNumber"
        >
          {{ ruleForm2.productNumber }}
          <!-- <el-input v-model="ruleForm2.productNumber" readonly="true"></el-input> -->
        </el-form-item>
        <el-form-item
          label="出库数量"
          prop="stockNum"
          
        >
          <el-input v-model="ruleForm2.stockNum" type="number" />
        </el-form-item>
        <el-form-item
          label="领用人"
          prop="receiveMan"
        >
          <el-input v-model="ruleForm2.receiveMan" />
        </el-form-item>
        <el-form-item
          label="领用原因"
          prop="receiveReason"
        >
          <el-input v-model="ruleForm2.receiveReason" />
        </el-form-item>
      </el-form>
    </DownloadIdentify>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import waves from "@/directive/waves"; // waves directive
import { parseTime, listTotree } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
import ListOpearteButton from "@/components/AllButton/button2";
import tableButton from "@/components/AllButton/button3";
import FormEdit from "./formEdit";
import DownloadIdentify from "@/components/FormDialog";
import { mapGetters } from "vuex";
import IdentifyContent from "./component/identifyContent";
import data from "./const";

export default {
  name: "Supply",
  components: {
    DownloadIdentify,
    IdentifyContent,
    Pagination,
    tableButton,
    ListOpearteButton,
    FormEdit
  },
  directives: { waves },
  filters: {
    typeFilter(type) {
      return calendarTypeKeyValue[type];
    }
  },
  data() {
    return {
      ruleForm1: {
        productId: "",
        productName: "",
        productNumber: "",
        productModel: "",
        productType: "",
        organName: "",
        topLimit: "",
        stockNum: "",
        filePath: [],
        receiveMan: ""
      },
      rules1: {
        stockNum: [
          { required: true, message: "请填写入库数量", trigger: "blur" },
         // { type:"number", message: "入库数量为数字", trigger: "blur" }
        ]
      },
      ruleForm2: {
        productId: "",
        productName: "",
        productNumber: "",
        productModel: "",
        productType: "",
        organName: "",
        topLimit: "",
        stockNum: "",
        receiveMan: "",
        filePath: []
      },
      rules2: {
        stockNum: [
          { required: true, message: "请填写出库数量", trigger: "blur" },
          // { type:"number", message: "出库数量为数字", trigger: "blur" }
        ],
        receiveMan: [
          { required: true, message: "请填写领用人", trigger: "blur" }
        ],
        receiveReason: [
          { required: true, message: "请填写领用原因", trigger: "blur" }
        ]
      },
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      loadList: false,
      paginationInfo: {
        sizeChange: e => {
          console.log(e);
        },
        currentChange: e => {
          this.$store.dispatch("supply/setListSearchParams", {
            current: e
          });
          this.getList(
            Object.assign({}, this.$store.state.supply.listSearchParams)
          );
        },
        current: 1,
        total: 10
      },
      formOptions: {
        inline: true,
        submitBtnText: "搜索",
        showResetBtn: true,
        searchParamsHandler: () => {
          console.log("搜索");
          this.getList(this.$store.state.supply.listSearchParams);
        },
        changevalue: params => {
          //   const forms=this.formOptions.forms.map(e=>{
          //      const key=e.prop
          //      e.defaultValue=params[key]
          //     return e
          //    })
          //  console.log(forms)
          console.log(params);
          this.$store.dispatch("supply/setListSearchParams", params);
        },
        resetBtnCallback: () => {
          this.$store.dispatch("supply/setListSearchParams", {});
          this.getList();
        },
        forms: [
          { prop: "productName", label: "备件名称" },

          { prop: "productNumber", label: "备件编号" },
          { prop: "productModel", label: "规格型号" },
          {
            prop: "deviceNumber",
            label: "类别",
            itemType: "select",
            options: [
              { value: 0, label: "自制" },
              { value: 1, label: "外购" }
            ]
          },
          {
            prop: "organId",
            label: "归属部门",
            itemType: "cascader",
            options: [
              { value: "", label: "部门1" },
              { value: 0, label: "部门2" },
              { value: 1, label: "部门3" }
            ]
          },

          {
            prop: "usageType",
            label: "通用/专用",
            itemType: "select",
            options: [
              { value: 0, label: "通用" },
              { value: 1, label: "专用" }
            ]
          }
        ]
      },
      columns: [
        { type: "index", prop: "repNumber", label: "序号" },

        {
          prop: "productName",
          label: "备件名称"
          // width: 100,
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.name ? deviceInfo.name :"";
          // },
        },
        {
          prop: "productNumber",
          label: "备件编号"
          // width: 100,
          // render: (row) => {
          //   const { deviceInfo } = row;
          //   return deviceInfo.deviceNumber ? deviceInfo.deviceNumber :"";
          // },
        },
        // { prop: "departmentName", label: "使用部门", minWidth: 180, render: (row) => {
        //     const { departmentInfo } = row;
        //     return departmentInfo.name ? departmentInfo.name :"";
        //   },},
        { prop: "productModel", label: "规格型号" },
        { prop: "productType", label: "类别" },
        { prop: "organName", label: "归属部门" },
        // {
        //   prop: "itemsSum",
        //   label: "点检项",
        //   slotName: "items-sum",
        //   minWidth: 180,
        // },
        { prop: "stockNum", label: "库存" },
        {
          prop: "productPrice",
          label: "单价"

          // slotName: "preview-column",
        },
        {
          prop: "usageType",
          label: "通用/专用",
          filter: "supplyType"
        },
        {
          prop: "operate",
          label: "操作",
          minWidth: 100,
          slotName: "operate-column",
          fixed: "right"
        }
      ],
      tableData: []
    };
  },

  watch: {
    formChange: () => {}
  },
  computed: {
    ...mapState(["supply", "app"])
  },
  created() {
    // 初始获取几个基本数据,分别为操作状态,按钮权限等
    (this.formOptions.forms = this.formOptions.forms.map(e => {
      const key = e.prop;
      const data = this.$store.state.supply.listSearchParams;
      e.defaultValue = data[key] || "";
      return e;
    })),
      // this.submitHandler=this.searchWithParams
      this.$store
        .dispatch(this.$store_url_button, {
          add: this.add,
          export: this.export,
          delete: this.delete,
          edit: this.edit,
          detail: this.detail,
          instock: this.instock,
          outstock: this.outstock,
          downloadTemplete: this.downloadTemplete,
          downloadIdentify: this.downloadIdentify
        })
        .then(async () => {
          // await this.$store.dispatch("app/getCodeList", []); //code转码
          const assetType = listTotree(
            this.$store.state.app.allCode.department
          );
          this.$set(this.formOptions.forms[4], "options", assetType);
          this.getList(); // 表格数据
        });

    // this.listQuery=this.$store.state.basicEquipment.listSearchParams||{}  //操作状态
  },
  methods: {
    dialogSubmit1() {
      this.$refs["ruleForm1"].validate(valid => {
        if (valid) {
          this.$store
            .dispatch("supply/saveInstock", this.ruleForm1)
            .then(res => {
              this.getList();
              this.dialogFormVisible1 = false;
            })
            .catch(err => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    dialogSubmit2() {
      this.$refs["ruleForm2"].validate(valid => {
        if (valid) {
          this.$store
            .dispatch("supply/saveOutStock", this.ruleForm2)
            .then(res => {
              this.getList();
              this.dialogFormVisible2 = false;
            })
            .catch(err => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 自定义该业务模块下的按钮方法
    instock(row) {
      console.log("instock", row);
      this.ruleForm1 = row;
      this.dialogFormVisible1 = true;
    },
    outstock(row) {
      console.log("outstock", row);
      this.ruleForm2 = row;
      this.dialogFormVisible2 = true;
    },
    add(row) {
      localStorage.removeItem("/supply/component/edit/index");
      this.$router.push("/supply/component/edit/index");
    },
    edit(row) {
      localStorage.setItem("/supply/component/edit/index", row.id);
      this.$router.push("/supply/component/edit/index");
      console.log("edit");
    },
    downloadIdentify(row) {
      console.log("下载设备标识卡");
      this.dialogFormVisible = true;
    },
    async downloadTemplete(ids) {
      console.log("下载导出模板");
      const download = await this.$store.dispatch("supply/downloadTemplete");
      // window.open(download.)
      console.log(download);
    },
    delete(row) {
      console.log(row);
      this.$confirm(`备件删除后不可恢复，确认删除？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$store
            .dispatch("supply/deleteDeviceInfo", row.id)
            .then(response => {
              this.$message({
                type: "success",
                message: "删除成功!"
              });
              this.getList();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "删除失败"
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    update() {},
    detail(row) {
      console.log(row);

      localStorage.setItem("/supply/component/detail", row.id);
      localStorage.setItem("/supply/component/detail/productId", row.productId);
      this.$router.push("/supply/component/detail");
    },
    import() {},
    export() {
      console.log("导出");
      this.$store.dispatch("supply/exportFile");
    },
    // 弹窗的关闭
    cancel1() {
      this.dialogFormVisible1 = false;
    },
    cancel2() {
      this.dialogFormVisible2 = false;
    },
    // 更新弹窗数据
    updateDialog() {
      console.log("更新并关闭弹窗");
      this.dialogFormVisible = false;
    },
    // 搜索按钮
    searchWithParams() {
      console.log("搜索");
    },
    async getList(args) {
      // this.listLoading = true
      console.log(args);
      await this.$store.dispatch("supply/requestDeviceList", args);
      this.paginationInfo.total = this.$store.state.supply.total;
    },
    handleFilter(args) {
      this.listQuery.page = 1;
      this.getList(args);
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: "操作成功",
        type: "success"
      });
      row.status = status;
    },
    sortChange(data) {
      const { prop, order } = data;
      if (prop === "id") {
        this.sortByID(order);
      }
    },
    sortByID(order) {
      if (order === "ascending") {
        this.listQuery.sort = "+id";
      } else {
        this.listQuery.sort = "-id";
      }
      this.handleFilter();
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        importance: 1,
        remark: "",
        timestamp: new Date(),
        title: "",
        status: "published",
        type: ""
      };
    },
    handleCreate() {
      // this.resetTemp();
      // this.dialogStatus = "create";
      // this.dialogFormVisible = true;
      // this.$nextTick(() => {
      //   this.$refs["dataForm"].clearValidate();
      // });
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.temp.timestamp = new Date(this.temp.timestamp);
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    handleDelete(row) {
      this.$notify({
        title: "成功",
        message: "删除成功",
        type: "success",
        duration: 2000
      });
      const index = this.list.indexOf(row);
      this.list.splice(index, 1);
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "timestamp") {
            return parseTime(v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
};
</script>

